<?php
// 开发者自定义函数、库、全部变量文件

/**
 * json数据输出 
 *
 */
function ajaxOutput($code, $msg, $data = array()) {
	$data = array(
		'code' => $code, 
		'msg'  => $msg,
		'data' => $data
	);

	$tmp = json_encode($data);
	echo $tmp;
	exit();
}

/**
 * 将非数组转化为数组 
 *
 */
function object2array($object) {
     $object =  json_decode( json_encode( $object),true);
     return  $object;
}

/**
 * 获取目录下面的文件或是文件夹 
 * @return array[]
 *           type : 1=目录 2=文件
 * 			 name : 名字
 */
function getFiles($folder) {
	if(!file_exists($folder)) {
		return array();
	}

	$data = array();
	$handle = opendir($folder);

	while(($file = readdir($handle)) !== false) {
		$sub_dir = $folder . $file;    //构建子目录路径
        if($file == '.' || $file == '..') {
            continue;
        } else if(is_dir($sub_dir)) {
        	$data[] = array('type' => 1, 'name' => $file, 'dir' => $folder . $file . '/');    
        } else {
        	$data[] = array('type' => 2, 'name' => $file, 'dir' => $folder . $file);    
        }
	}

	return $data;
}

/**
 * 创建树的json数据 
 * 
 */
function getTreeData($data, $pid = 0, $project, $pre) {
	if(!is_array($data)) {
		return json_encode(array());
	}

	$res = array();
	foreach($data as $key => $val) {
		//去除具体的目录地址
		$projectPre = $pre . $project;
		$val['dir'] = str_replace($projectPre, '', $val['dir']);

		if($val['type'] == 2) {
			$tmp = array('id' => $pid. '_' . $key, 'pId' => $pid, 'name' => $val['name'], 'isParent' => false, 'dir' =>  $val['dir'], 'project' => $project);
		} else {
			$tmp = array('id' => $pid. '_' . $key, 'pId' => $pid, 'name' => $val['name'], 'isParent' => true, 'dir' =>  $val['dir'], 'project' => $project);
		}
		
		$res[] = $tmp;
	}

	return $res;
}

/**
 * 删除目录
 */
function delDir($dir) {
  	//先删除目录下的文件
  	$dh = opendir($dir);
  	while ($file = readdir($dh)) {
		if($file  != "." && $file != "..") {
			$fullpath =$dir."/".$file;

      		if(!is_dir($fullpath)) {
          		unlink($fullpath);
      		} else {
          		delDir($fullpath);
      		}
      	}
  	}
 
  	closedir($dh);
  	//删除当前文件夹
  	if(rmdir($dir)) {
    	return true;
  	} else {
    	return false;
  	}
}

?>
